/**
 * CopyKnot.cpp
 * Coyright (c) 2009 Xiaofeng Gu. All Rights Reserved.
 * Author : Xiaofeng Gu
 *
 * Creation Data : 2009/07/13
 */

#include "stdafx.h"
#include "CopyKnot.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

HRESULT CCopyKnot::OnExecute()
{
	HRESULT hr = S_OK;
	hr = __super::OnExecute();
	if (hr != S_OK)
	{
		return hr;
	}

	CSKInfo* pSKInfo = GetBlockInfo<CSKInfo>(SKINFO_INSTANCE);
	CTimeline* pTimeline = pSKInfo->GetTimeline();
	CFamily* pFamily = pTimeline->GetActiveFamily();
	if (pFamily == NULL) return E_FAIL;
	m_pKnot = pFamily->GetActiveChild();
	CKnot* pNewOne = Copy(m_pKnot);
	pFamily->Add(pNewOne);
	pNewOne->SetActive(false);
	pNewOne->SetTime(pFamily->GetMaxTime() + 1);

	return S_OK;
}

CKnot* CCopyKnot::Copy(CKnot* pKnot)
{
	CKnot* pNew = pKnot->Copy();
	Nodes* pNewNodes = pNew->GetNodes();
	CTransNode* pTopNode = pKnot->GetTopNode();
	CTransNode* pNewTopNode = pTopNode->Copy(pNew);
	pNewNodes->push_back(pNewTopNode);

	Copy(pTopNode, pNewTopNode, pNewNodes);

	pNew->SetTopNode(pNewTopNode);

	return pNew;
}

void CCopyKnot::Copy(CTransNode* pNode,
				   CTransNode* pNewNode,
				   Nodes* pNewNodes)
{
	Nodes* pNodes = pNode->GetChildren();
	for (Nodes::iterator it = pNodes->begin();
		it != pNodes->end(); it ++)
	{
		CTransNode* pChildNode = *it;
		CTransNode* pChildNewNode = pChildNode->Copy(pNewNode->GetParentKnot());
		pNewNodes->push_back(pChildNewNode);

		pChildNewNode->SetParent(pNewNode);
		pNewNode->AddChild(pChildNewNode);

		Copy(pChildNode, pChildNewNode, pNewNodes);
	}
}